from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings


def generate_open_id_signature(openid):
    # 创建serializer实例对象
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=600)
    # 调用dumps进行加密,
    data = {'openid': openid}
    openid_sign = serializer.dumps(data) # bytes类型
    # 转成str返回
    return openid_sign.decode()


def check_open_id(openid_sign):
    # 创建serializer实例对象
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=600)

    # 2.调用loads进行解密
    try:
        data = serializer.loads(openid_sign)  # 输入 反序列化: 字典转模型
        return data.get('openid')

    except BadData:
        return None
